package com.xiaomei.manager.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xiaomei.manager.model.Banner;
import com.xiaomei.manager.service.IBannerService;
import com.xiaomei.manager.utils.Constants;
import com.xiaomei.manager.web.aliyun.OSS.AliyunUpload;
import com.xiaomei.manager.web.dto.req.BannerQueryDto;
import com.xiaomei.manager.web.page.Page;

@Controller
@RequestMapping("/banner")
public class BannerController {
	@Autowired
	private IBannerService iBannerService;
	
	private Logger logger = Logger.getLogger(BannerController.class);
	
	@RequiresPermissions("banner:view")
	@RequestMapping()
	public String list(Model model,BannerQueryDto dto,Page<Banner>page ){
		iBannerService.getBannerForList(dto, page);
		model.addAttribute("dto", dto);
		model.addAttribute("page", page);
		return "banner/list";
	}
	
	/**
     * banner图添加
     * @param model
     * @return
     */
	 @RequiresPermissions("banner:create")
	    @RequestMapping( value = "/create",method = RequestMethod.GET)
	    public String showCreateForm(Model model) {	        
	        model.addAttribute("ban", new Banner());
	        model.addAttribute("op", "新增");
	        return "banner/edit";
	    }
	 @RequiresPermissions("banner:create")
	    @RequestMapping(value = "/create",method = RequestMethod.POST)
	    public String create(Banner ban ,@RequestParam("files") MultipartFile[] files, RedirectAttributes redirectAttributes) {
	    
	    	//获取活动ID
	    	Integer backid = iBannerService.selectMaxId();
	    	Integer id = 0;
	    	if(backid == null){
	    		id = 1;
	    	}else{
	    		id = backid + 1;
	    	}
	    	ban.setId(id);
	    	 if(files != null && files.length > 0){  
		            //循环获取file数组中得文件  
		    		int i ;
		            for(i = 0;i<files.length;i++){  
		                MultipartFile file = files[i];	                
		                String fileName = file.getOriginalFilename();	                
		                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
			 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
			                String finalFileName = "banner/"+id+"/img_"+(i+1)+extention;
			                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
			                if(i == 0){
			                	ban.setBannerUrl(url);
			                }
			            try{
			                AliyunUpload.getInstance();	                
			                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
			                }catch (Exception e) {
								logger.info("新增Banner图！");
							}	                  
		                }  
		            } 
		    	}	     	
	    	iBannerService.createBanner(ban);
	        redirectAttributes.addFlashAttribute("msg", "新增成功");
	        return "redirect:/banner";
	    }
	 /**
	     * 更新Banner图内容
	     * @param id
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("banner:update")
	    @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	    public String showUpdateForm(@PathVariable("id") Integer id, Model model) {
	        model.addAttribute("ban", iBannerService.findOne(id));
	        model.addAttribute("op", "修改");
	        return "banner/edit";
	    }

	    @RequiresPermissions("banner:update")
	    @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
	    public String update(Banner ban, @RequestParam("files") MultipartFile[] files , @PathVariable("id") Integer id, RedirectAttributes redirectAttributes, HttpServletRequest request){	    		    
	    	if(files != null && files.length > 0){  
	            //循环获取file数组中得文件  
	    		int i ;
	            for(i = 0;i<files.length;i++){  
	                MultipartFile file = files[i];	                
	                String fileName = file.getOriginalFilename();	                
	                if(file != null && file.getSize() > 0 && fileName != null && !fileName.equals("")){	       	
		 	            String extention = fileName.substring(fileName.lastIndexOf("."), fileName.length());	                         
		                String finalFileName = "banner/"+id+"/img_"+(i+1)+extention;
		                String url = AliyunUpload.getOSSUrl(Constants.OSS_BUCKET_COMMON, finalFileName);
		                if(i == 0){
		                	ban.setBannerUrl(url);
		                }
		            try{
		                AliyunUpload.getInstance();	                
		                AliyunUpload.uploadMultipartFile(finalFileName, Constants.OSS_BUCKET_COMMON, file);
		                }catch (Exception e) {
							logger.info("修改banner失败！");
						}	                  
	                }  
	            } 
	    	}
	    	//banner backban = iBannerService.selectbannerById(id);
	    	//ban.setVersion(backban.getVersion());
	        iBannerService.updateBanner(ban);
	        redirectAttributes.addFlashAttribute("msg", "修改成功");
	        return "redirect:/banner";
	    }
	    /**
	     * 删除n
	     * @param id
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("banner:delete")
	    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
	    public String showDeleteForm(@PathVariable("id") Integer id, Model model) {	       
	    	model.addAttribute("ban", iBannerService.findOne(id));
	        model.addAttribute("op", "删除");
	        return "banner/edit";
	    }
	    
	    
	    
	    @RequiresPermissions("banner:delete")
	    @RequestMapping(value="/{id}/delete" ,method=RequestMethod.POST)
	    public String delete(@PathVariable("id") Integer id,RedirectAttributes redirectAttributes ){
	    	  Banner ban = iBannerService.findOne(id);
		        if(ban.getBannerUrl()!=null && !ban.getBannerUrl().equals("")){
		        	 AliyunUpload.removeOssObject(ban.getBannerUrl());
		        }
		        iBannerService.deleteBanner(id);
		        redirectAttributes.addFlashAttribute("msg", "删除成功");
		        return "redirect:/banner";
	    }
}
